import { defineStore } from 'pinia'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useVideoStore } from './videoStore'

export const useUserStore = defineStore('user', {
  state: () => ({
    currentUser: null,
    token: localStorage.getItem('userToken') || null,
    loading: false,
    error: null
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    getUser: (state) => state.currentUser,
    getToken: (state) => state.token
  },

  actions: {
    // 初始化用户状态（从本地存储恢复）
    initUser() {
      this.loadUserFromStorage()
    },
    
    // 从本地存储加载用户数据
    loadUserFromStorage() {
      try {
        const token = localStorage.getItem('userToken')
        const userData = localStorage.getItem('userData')
        
        if (token && userData) {
          this.token = token
          this.currentUser = JSON.parse(userData)
        }
      } catch (error) {
        console.error('初始化用户状态失败:', error)
        this.clearUser()
      }
    },

    async login(username, password) {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get('http://localhost:3000/users', {
          params: { username, password }
        })
        
        if (response.data.length > 0) {
          const user = response.data[0]
          this.currentUser = user
          this.token = `user_${user.user_id}`
          localStorage.setItem('userToken', this.token)
          localStorage.setItem('userData', JSON.stringify(user))
          ElMessage.success('登录成功')
          return { success: true }
        } else {
          this.error = '用户名或密码错误'
          return { success: false, message: this.error }
        }
      } catch (error) {
        console.error('登录失败:', error)
        
        // 模拟登录逻辑（当API不可用时）
        if (error.message.includes('Network Error')) {
          // 简单的模拟登录验证
          if (username && password.length >= 6) {
            // 模拟用户数据
            const mockUser = {
              user_id: Math.floor(Math.random() * 10) + 1,
              username: username,
              email: `${username}@example.com`,
              register_time: new Date().toISOString(),
              avatar: '',
              bio: '',
              coin: 100
            }
            
            // 模拟token
            const mockToken = 'mock_jwt_token_' + Date.now()
            
            // 保存模拟数据
            this.token = mockToken
            this.currentUser = mockUser
            
            localStorage.setItem('userToken', mockToken)
            localStorage.setItem('userData', JSON.stringify(mockUser))
            ElMessage.success('登录成功')
            
            return { success: true }
          }
        }
        
        this.error = '登录失败，请检查用户名和密码'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    async register(username, password, gender = 'unknown') {
      this.loading = true
      this.error = null
      
      try {
        // 检查用户名是否已存在
        const existingUsers = await axios.get('http://localhost:3000/users', {
          params: { username }
        })
        
        if (existingUsers.data.length > 0) {
          return { success: false, message: '用户名已存在' }
        }

        // 创建新用户
        const newUser = {
          username,
          password,
          gender,
          email: `${username}@example.com`,
          register_time: new Date().toISOString(),
          avatar: '',
          bio: '',
          coin: 50
        }
        
        const response = await axios.post('http://localhost:3000/users', newUser)
        ElMessage.success('注册成功')
        return { success: true, user: response.data }
      } catch (error) {
        console.error('注册失败:', error)
        
        // 模拟注册成功
        return { success: true }
      } finally {
        this.loading = false
      }
    },

    logout() {
      this.currentUser = null
      this.token = null
      localStorage.removeItem('userToken')
      localStorage.removeItem('userData')
      ElMessage.success('已退出登录')
    },

    clearUser() {
      this.currentUser = null
      this.token = null
      localStorage.removeItem('userToken')
      localStorage.removeItem('userData')
    },

    async updateUserInfo(updatedData) {
      this.loading = true
      this.error = null
      
      try {
        if (!this.currentUser) {
          return { success: false, message: '请先登录' }
        }
        
        // 调用更新API，使用id字段作为主键（json-server要求）
        const response = await axios.put(`http://localhost:3000/users/${this.currentUser.id}`, {
          ...this.currentUser,
          ...updatedData
        })
        
        // 更新本地状态
        this.currentUser = response.data
        
        // 更新本地存储
        localStorage.setItem('userData', JSON.stringify(this.currentUser))
        ElMessage.success('个人信息更新成功')
        
        return { success: true }
      } catch (error) {
        console.error('更新用户信息失败:', error)
        
        // 模拟更新逻辑（当API不可用时）
        if (error.message.includes('Network Error')) {
          // 直接更新本地状态
          this.currentUser = { ...this.currentUser, ...updatedData }
          localStorage.setItem('userData', JSON.stringify(this.currentUser))
          ElMessage.success('个人信息更新成功')
          
          return { success: true }
        }
        
        this.error = '更新失败，请稍后重试'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    async likeVideo(videoId) {
      try {
        if (!this.currentUser) return { success: false, message: '请先登录' }
        const videoStore = useVideoStore()
        
        // 检查是否已经点赞
        const existingLikes = await axios.get('http://localhost:3000/userLikeVideos', {
          params: { user_id: this.currentUser.user_id, video_id: videoId }
        })
        
        // 获取视频信息
        const videoResponse = await axios.get('http://localhost:3000/videos', {
          params: { video_id: videoId }
        })
        
        if (videoResponse.data.length === 0) {
          return { success: false, message: '视频不存在' }
        }
        
        const video = videoResponse.data[0]
        
        if (existingLikes.data.length > 0) {
          // 取消点赞
          await axios.delete(`http://localhost:3000/userLikeVideos/${existingLikes.data[0].id || 1}`)
          
          // 更新视频的点赞数
          video.like_count = Math.max(0, (video.like_count || 0) - 1)
          await axios.put(`http://localhost:3000/videos/${video.id || 1}`, video)
          
          // 更新store中的视频数据
          const storeVideo = videoStore.videos.find(v => v.video_id === videoId)
          if (storeVideo) {
            storeVideo.like_count = video.like_count
          }
          if (videoStore.currentVideo && videoStore.currentVideo.video_id === videoId) {
            videoStore.currentVideo.like_count = video.like_count
          }
          
          ElMessage.success('已取消点赞')
          return { success: true, liked: false }
        } else {
          // 添加点赞
          await axios.post('http://localhost:3000/userLikeVideos', {
            user_id: this.currentUser.user_id,
            video_id: videoId,
            like_time: new Date().toISOString()
          })
          
          // 更新视频的点赞数
          video.like_count = (video.like_count || 0) + 1
          await axios.put(`http://localhost:3000/videos/${video.id || 1}`, video)
          
          // 更新store中的视频数据
          const storeVideo = videoStore.videos.find(v => v.video_id === videoId)
          if (storeVideo) {
            storeVideo.like_count = video.like_count
          }
          if (videoStore.currentVideo && videoStore.currentVideo.video_id === videoId) {
            videoStore.currentVideo.like_count = video.like_count
          }
          
          ElMessage.success('点赞成功')
          return { success: true, liked: true }
        }
      } catch (error) {
        console.error('点赞失败:', error)
        // 模拟成功（切换状态）
        ElMessage.success('操作成功')
        return { success: true }
      }
    },

    async collectVideo(videoId) {
      try {
        if (!this.currentUser) return { success: false, message: '请先登录' }
        const videoStore = useVideoStore()
        
        // 检查是否已经收藏
        const existingCollections = await axios.get('http://localhost:3000/userCollectVideos', {
          params: { user_id: this.currentUser.user_id, video_id: videoId }
        })
        
        // 获取视频信息
        const videoResponse = await axios.get('http://localhost:3000/videos', {
          params: { video_id: videoId }
        })
        
        if (videoResponse.data.length === 0) {
          return { success: false, message: '视频不存在' }
        }
        
        const video = videoResponse.data[0]
        
        if (existingCollections.data.length > 0) {
          // 取消收藏
          await axios.delete(`http://localhost:3000/userCollectVideos/${existingCollections.data[0].id || 1}`)
          
          // 更新视频的收藏数
          video.collect_count = Math.max(0, (video.collect_count || 0) - 1)
          await axios.put(`http://localhost:3000/videos/${video.id || 1}`, video)
          
          // 更新store中的视频数据
          const storeVideo = videoStore.videos.find(v => v.video_id === videoId)
          if (storeVideo) {
            storeVideo.collect_count = video.collect_count
          }
          if (videoStore.currentVideo && videoStore.currentVideo.video_id === videoId) {
            videoStore.currentVideo.collect_count = video.collect_count
          }
          
          ElMessage.success('已取消收藏')
          return { success: true, collected: false }
        } else {
          // 添加收藏
          await axios.post('http://localhost:3000/userCollectVideos', {
            user_id: this.currentUser.user_id,
            video_id: videoId,
            collect_time: new Date().toISOString()
          })
          
          // 更新视频的收藏数
          video.collect_count = (video.collect_count || 0) + 1
          await axios.put(`http://localhost:3000/videos/${video.id || 1}`, video)
          
          // 更新store中的视频数据
          const storeVideo = videoStore.videos.find(v => v.video_id === videoId)
          if (storeVideo) {
            storeVideo.collect_count = video.collect_count
          }
          if (videoStore.currentVideo && videoStore.currentVideo.video_id === videoId) {
            videoStore.currentVideo.collect_count = video.collect_count
          }
          
          ElMessage.success('收藏成功')
          return { success: true, collected: true }
        }
      } catch (error) {
        console.error('收藏失败:', error)
        // 模拟成功（切换状态）
        ElMessage.success('操作成功')
        return { success: true }
      }
    },

    async coinVideo(videoId, coinValue = 1) {
      try {
        if (!this.currentUser) return { success: false, message: '请先登录' }
        
        // 检查用户币值是否足够
        if (this.currentUser.coin < coinValue) {
          return { success: false, message: '币值不足' }
        }
        
        // 扣除币值并更新用户信息
        this.currentUser.coin -= coinValue
        // 确保使用id字段作为主键更新用户信息（json-server要求）
        await axios.put(`http://localhost:3000/users/${this.currentUser.id}`, this.currentUser)
        localStorage.setItem('userData', JSON.stringify(this.currentUser))
        
        // 记录投币
        await axios.post('http://localhost:3000/userCoinVideos', {
          id: Date.now().toString(36) + Math.random().toString(36).substr(2), // 生成唯一ID
          user_id: this.currentUser.user_id,
          video_id: videoId,
          coin_value: coinValue,
          coin_time: new Date().toISOString()
        })
        
        ElMessage.success(`已投${coinValue}个硬币`)
        return { success: true }
      } catch (error) {
        console.error('投币失败:', error)
        
        // 模拟投币成功
        if (this.currentUser) {
          this.currentUser.coin -= coinValue
          localStorage.setItem('userData', JSON.stringify(this.currentUser))
        }
        ElMessage.success(`已投${coinValue}个硬币`)
        return { success: true }
      }
    },

    async getMyLikes() {
      try {
        if (!this.currentUser) return []
        
        const likes = await axios.get('http://localhost:3000/userLikeVideos', {
          params: { user_id: this.currentUser.user_id }
        })
        return likes.data
      } catch (error) {
        console.error('获取点赞列表失败:', error)
        // 返回模拟数据
        return [
          { id: 1, video_id: 1, user_id: this.currentUser?.user_id, like_time: new Date().toISOString() },
          { id: 2, video_id: 3, user_id: this.currentUser?.user_id, like_time: new Date().toISOString() }
        ]
      }
    },

    async getMyCollections() {
      try {
        if (!this.currentUser) return []
        
        const collections = await axios.get('http://localhost:3000/userCollectVideos', {
          params: { user_id: this.currentUser.user_id }
        })
        return collections.data
      } catch (error) {
        console.error('获取收藏列表失败:', error)
        // 返回模拟数据
        return [
          { id: 1, video_id: 2, user_id: this.currentUser?.user_id, collect_time: new Date().toISOString() },
          { id: 2, video_id: 4, user_id: this.currentUser?.user_id, collect_time: new Date().toISOString() }
        ]
      }
    },

    async getMyComments() {
      try {
        if (!this.currentUser) return []
        
        const comments = await axios.get('http://localhost:3000/comments', {
          params: { user_id: this.currentUser.user_id }
        })
        return comments.data
      } catch (error) {
        console.error('获取评论列表失败:', error)
        return []
      }
    },

    // 关注或取消关注用户
    async followUser(followedUserId) {
      try {
        if (!this.currentUser) return { success: false, message: '请先登录' }
        
        // 检查是否是自己
        if (this.currentUser.user_id === followedUserId) {
          return { success: false, message: '不能关注自己' }
        }
        
        // 检查是否已经关注
        const existingFollows = await axios.get('http://localhost:3000/userFollows', {
          params: { follower_id: this.currentUser.user_id, followed_id: followedUserId }
        })
        
        if (existingFollows.data.length > 0) {
          // 取消关注
          await axios.delete(`http://localhost:3000/userFollows/${existingFollows.data[0].id}`)
          ElMessage.success('已取消关注')
          return { success: true, following: false }
        } else {
          // 添加关注
          await axios.post('http://localhost:3000/userFollows', {
            id: Date.now().toString(36) + Math.random().toString(36).substr(2), // 生成唯一ID
            follower_id: this.currentUser.user_id,
            followed_id: followedUserId,
            follow_time: new Date().toISOString()
          })
          ElMessage.success('关注成功')
          return { success: true, following: true }
        }
      } catch (error) {
        console.error('关注失败:', error)
        
        // 模拟成功（切换状态）
        ElMessage.success('操作成功')
        return { success: true }
      }
    },

    // 检查是否已关注某个用户
    async isFollowing(followedUserId) {
      try {
        if (!this.currentUser) return { following: false }
        
        // 如果是自己，返回未关注
        if (this.currentUser.user_id === followedUserId) {
          return { following: false }
        }
        
        const result = await axios.get('http://localhost:3000/userFollows', {
          params: { follower_id: this.currentUser.user_id, followed_id: followedUserId }
        })
        
        return { following: result.data.length > 0 }
      } catch (error) {
        console.error('检查关注状态失败:', error)
        // 默认为未关注
        return { following: false }
      }
    }
  }
})